package leetcode;

public class Solutin29 {
    public static void main(String[] args) {
        // -2147483648
        // -1
        divide(-2147483648, -1);
    }

    public static int divide(int dividend, int divisor) {
        if(divisor == 0) return 0;
        // 利用递归调用, 把除法变成减法，
        // 例如10/3，看成是 第一次跟3比较，10>3；再跟10比较，10 > 6；再 6 + 6, 再跟10比较, 10 < 12; 10 - 6 = 4, 把5再跟3比较，进入第二轮；
        // 负数先转成正数在递归
        int dividendFlag = 0;
        int divisorFlag = 0;
        if(dividend < 0){
            dividendFlag = 1;
            dividend = -dividend;
            if(dividend == Integer.MIN_VALUE){

            }
        }

        if(divisor < 0){
            divisorFlag = 1;
            divisor = -divisor;
        }

        return (dividendFlag ^ divisorFlag) == 1 ? -recurse(dividend, divisor) : recurse(dividend, divisor);
    }

    public static int recurse(int dividend, int divisor){
        if(dividend < divisor){
            return 0;
        }
        int pre = divisor;
        int temp = divisor;
        int count = 0;
        while(dividend >= temp){
            pre = temp;
            temp += temp;
            if(count == 0){
                count = 1;
            }else{
                count += count;
            }
        }

        return count + recurse(dividend - pre, divisor);
    }
}
